import { LegendControl } from '@u/control'
// 根据点击返回要素，创建popup html进行展示
export const createPopup = (features) => {
  const renderArr = (arr) => arr.toString().replaceAll(',', '')
  const renderProperty = ({ key, value }) => `
    <div class="property">
      <span class="property_key"><b>${key}：</b></span>
      <span class="property_value">${value}</span>
    </div>`
  const renderFeature = (feature) =>
    `<div class="popup_feature">
      <div class="title">属性信息</div>
      <div class="content">
      ${renderArr(
        Object.keys(feature.properties).map((key) =>
          renderProperty({ key, value: feature.properties[key] })
        )
      )}
      </div>
    </div>`
  return `<div class="popup_features">
        ${renderArr(features.map(renderFeature))}
      </div>`
}

// 添加图例
export const addLegend = (map, layers) => {
  // 传递图层数据，找到适合图例的图层，返回首次的那个图例
  if (!layers.length) {
    return false
  }

  // 直接传递的图层id
  if (typeof layers === 'string') {
    let layerId = layers
    const layer = map.getLayer(layerId)
    const color = map.getPaintProperty(layerId, `${layer.type}-color`)
    if (color && Array.isArray(color)) {
      if (color[0] == 'step') {
        // step 表达式处理
        const isColor = (str) =>
          str.toUpperCase().includes('RGB') || str.startsWith('#')
        const legends = color.slice(3).reduce((acc, cur) => {
          const len = acc.length
          let obj = {}
          if (len === 0 || !isColor(cur + '')) {
            // 不是颜色，数值
            obj.name = cur
          } else if (isColor(cur + '')) {
            obj.color = cur
          }
          acc.push(obj)
          return acc
        }, [])

        let res = []
        for (let index = 0; index < legends.length; index += 2) {
          let obj = Object.assign({}, legends[index], legends[index + 1])

          res.push(obj)
        }
        console.log(res)
        const legendControl = new LegendControl(res)
        map.addControl(legendControl, 'bottom-right')
        return legendControl
      }
    }
  }

  // 地图编辑器配置色块处理（stops）
  let legendControl = null

  // 存在多个图层，排除无关的图层，并使用第一个作为图例色阶
  for (let index = 0; index < layers.length; index++) {
    let layerId = layers[index].id
    const layer = map.getLayer(layerId)
    const color = map.getPaintProperty(layerId, `${layer.type}-color`)
    if (color) {
      const legends = []
      if (color.stops) {
        color.stops.forEach((item) => {
          let obj = {
            name: item[0],
            color: item[1],
          }
          legends.push(obj)
        })
      }
      if (!legends.length) {
        continue
      }
      console.log(legends)
      legendControl = new LegendControl(legends)
      map.addControl(legendControl, 'bottom-right')
      break
    } else {
      continue
    }
  }

  if (legendControl) {
    return legendControl
  } else {
    return false
  }
}
